/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.portalnahouby.implementation.daoimplementation;

import cz.muni.fi.pa165.portalnahouby.api.dto.Edibility;
import cz.muni.fi.pa165.portalnahouby.implementation.daointerface.MushroomDAO;
import cz.muni.fi.pa165.portalnahouby.implementation.entity.Mushroom;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of MushroomDAO interface
 *
 * @author Jakub Kutil
 */
@Repository
@Transactional
public class MushroomDAOImpl implements MushroomDAO {

@PersistenceContext
    private EntityManager em;
    
    @Override
    public void addMushroom(Mushroom mushroom) {
        if (mushroom == null) {
            throw new NullPointerException("Mushroom can not be null.");
        }

        if (mushroom.getId() != null) {
            throw new IllegalArgumentException("Id of mushroom must be null");
        }

        em.persist(mushroom);
    }

    
    @Override
    public void editMushroom(Mushroom mushroom) {
        if (mushroom == null) {
            throw new NullPointerException("Mushroom can not be null.");
        }

        if (mushroom.getId() == null) {
            throw new NullPointerException("Id of mushroom can not be null.");
        }

        em.merge(mushroom);
    }

    
    @Override
    public void deleteMushroom(Long id) {
        if (id == null) {
            throw new NullPointerException("Id of mushroom can not be null.");
        }

        Mushroom mushroom = em.find(Mushroom.class, id);

        em.remove(mushroom);
    }

    
    @Override
    public Mushroom findMushroom(Long id) {
        if (id == null) {
            throw new NullPointerException("Id of mushroom can not be null.");
        }

        Mushroom mushroom = em.find(Mushroom.class, id);

        return mushroom;
    }
    
    
    @Override
    public List<Mushroom> getListSortByName() {
        TypedQuery<Mushroom> query = em.createQuery("SELECT m FROM Mushroom m ORDER BY name", Mushroom.class);
        List<Mushroom> results = query.getResultList();
        return results;
    }

    
    @Override
    public List<Mushroom> getListByEdibility(Edibility edibility) {
        TypedQuery<Mushroom> query = em.createQuery("SELECT m FROM Mushroom m WHERE m.edibility ='" + edibility + "' ORDER BY name", Mushroom.class);
        List<Mushroom> results = query.getResultList();
        return results;
    }
}
